<?php
namespace App\Admin\Controllers\Purchase;

use App\Models\Basics\Supplier;
use App\Models\Product\ProductClassify;
use Encore\Admin\Controllers\AdminController;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Request;
use Symfony\Component\HttpFoundation\StreamedResponse;
class NotDeliveredController extends AdminController{

    protected $title = '未交货清单';

    protected $filters = [
        'start_date' => null,
        'end_date' => null,
        'supplier_id' => null,
        'classify_id' => null,
    ];

    protected $headersField = [
        'supplier_id',
        'classify_id',
        'not_delivery_num',
        'not_delivery_rmb',
    ];

    protected function grid()
    {
        $filtersField = array_keys($this->filters);
        $filters = $this->_getFilters($filtersField);
        $this->_initFilters($filters);
        $query = $this->_initQuery($filters);
        $_query = clone $query;
        $paginator = $this->_paginator($query);
        $total = $this->_sum($_query);
        $action = getAction($filtersField);
        $filtersBlade = [];
        $filtersBlade['start_date'] = $this->filters['start_date'];
        $filtersBlade['end_date'] = $this->filters['end_date'];
        $filtersBlade['supplier_id'] = getOptions(Supplier::options(),$this->filters['supplier_id']);
        $filtersBlade['classify_id'] = getOptions(ProductClassify::options(),$this->filters['classify_id']);
        $downloadUrl = '/xqc/purchase/not-delivered-download?' . http_build_query(array_merge(Request::all(),['_export_' => true]));
        $headers = $this->headersField;
        return view('purchase.not-delivered.index', compact('paginator','total','headers','action','filtersBlade','downloadUrl'));
    }

    private function _getFilters($filtersField){
        $startDate = request('start_date');
        $endDate = request('end_date');
        $reportDate = $this->__reportDate($startDate,$endDate);
        $filters = [];
        foreach ($filtersField as $field){
            if(array_key_exists($field,$reportDate)){
                $filters[$field] = $reportDate[$field];
            }else{
                $filters[$field] = request($field);
            }
        }
        return $filters;
    }

    private function _initFilters($filters){
        foreach ($filters as $field => $filter){
            $this->filters[$field] = $filter;
        }
    }

    private function __reportDate($start,$end){
        if(is_null($start) && is_null($end)){
            $startDate = date('Y-m-01');
            $endDate = date('Y-m-d');
        }elseif(!is_null($start) && is_null($end)){
            $startDate = $start;
            $endDate = strtotime($start) > time() ? date('Y-m-d') : date('Y-m-t',strtotime($start));
        }elseif(is_null($start) && !is_null($end)){
            $startDate = date('Y-m-01',strtotime($end));
            $endDate = $end;
        }else{
            $startDate = $start;
            $endDate = $end;
        }
        return ['start_date' => $startDate,'end_date' => $endDate];
    }

    private function _initQuery($filters){
        $query = DB::table('purchase_order_detail as pod')
            ->leftjoin('purchase_order as po','po.purchase_no','=','pod.purchase_no')
            ->leftjoin('product_sku as ps','ps.id','=','pod.psku_id')
            ->where('po.status',2); //已下单
        foreach ($filters as $field => $filter){
            if(!$filter)continue;
            if($field == 'start_date'){
                $query->where('po.order_at','>=',$filter.' 00:00:00');
            }
            if($field == 'end_date'){
                $query->where('po.order_at','<=',$filter.' 23:59:59');
            }
            if($field == 'classify_id'){
                $query->where('ps.classify_id',$filter);
            }
            if($field == 'supplier_id'){
                $query->where('po.supplier_id',$filter);
            }
        }
        return $query;
    }

    private function _sum($query){
        $sum = $query->select(DB::raw($this->__getSumFields()))->first();
        return toArray($sum);
    }

    private function _paginator($query){
        $query->select(DB::raw('po.supplier_id,ps.classify_id,'.$this->__getSumFields()))->groupBy('po.supplier_id','ps.classify_id');
        return $query->paginate((int) (request("per_page",10)))->appends(Request::input());
    }

    private function __getSumFields(){
        $re = 'sum(IFNULL(pod.order_num,0) - IFNULL(pod.rgoods_num,0)) as not_delivery_num';
        $re .= ',sum((IFNULL(pod.order_num,0) - IFNULL(pod.rgoods_num,0)) * IFNULL(pod.supplier_price,0)) as not_delivery_rmb';
        return $re;
    }

    public function download(){
        $filtersField = array_keys($this->filters);
        $filters = $this->_getFilters($filtersField);
        $query = $this->_initQuery($filters);
        $query->select(DB::raw('po.supplier_id,ps.classify_id,'.$this->__getSumFields()))->groupBy('po.supplier_id','ps.classify_id');
        $this->_exeDownload($query);
    }

    private function _exeDownload($query){
        $head = ['供应商','品类','未交货数量','未交货金额'];
        set_time_limit(0);
        $response = new StreamedResponse(null, 200, [
            'Content-Type'        => 'text/csv;charset=utf-8',
            'Content-Disposition' => 'attachment;filename="未交货清单.csv"',
        ]);
        $response->setCallback(function () use ($head, $query) {
            $fp = fopen('php://output', 'w');
            fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF));
            fputcsv($fp, $head);
            $re = $query->get();
            $data = $this->__getData($re);
            foreach ($data as $item) {
                fputcsv($fp, $item);
            }
            fclose($fp);
        });
        $response->send();
        exit(0);
    }

    private function __getData($re)
    {
        foreach ($re as $row){
            $temp = [];
            $temp['supplier'] = Supplier::getNameById($row->supplier_id);
            $temp['classify_id'] = ProductClassify::getTitleById($row->classify_id);
            $temp['not_delivery_num'] = $row->not_delivery_num;
            $temp['not_delivery_rmb'] = $row->not_delivery_rmb;
            yield $temp;
        }
    }
}
